from flask import Blueprint, render_template, jsonify, request
from models.entity.facility_type import FacilityType
from models.entity.facility import Facility
import json
from utils.result import result


"""
这个文件完成的是对模块的管理，实现对模块的添加，删除和修改,查看
"""
mod = Blueprint("core_facility_type", __name__, url_prefix="/core/facility_type", template_folder="templates", static_folder="static")


# 得到全部的类别
@mod.route("/get_all/", methods=["GET", "POST"])
def get_all():
    """返回模块列表，这个方法可能压根就用不上,用post"""
    # 请求数据格式：无
    facility_types = [item.to_dict() for item in FacilityType().get_list_all()]  # 得到所有节点
    return result(success=1, data=facility_types)


@mod.route("/del/", methods=["GET", "POST"])
def del_facility_type(*args, **kargs):
    """删除设施列表,如果有子类，则不能删除"""
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    facility_type = FacilityType().get_entity_by_id(dict["id"])
    if not facility_type:
        return result(success=0, error_code=-1, error_msg="设施或建筑物不存在")
    if len(Facility.get_facilities_by_facility_type_id(facility_type.id))!=0:
        return result(success=0, error_code=-1, error_msg="该设施类型依然存在下属设施")
    if facility_type.delete():
        return result(success=1)
    else:
        return result(success=1, error_code=-2, error_msg="未知错误")


@mod.route("/add/", methods=["GET", "POST"])
def add_facility_type(*args, **kargs):
    """增加设施类型列表"""
    """
    {
    "name":"jdd",
    "code":"21dddX",
    "description":"djhhh",
    "icon":"dddfdf",
    "dis_order":1,
    "status":0
    }
    """
    a = request.data
    try:
        dict = json.loads(a.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if 'id' in dict:
        dict.pop('id')
    if 'name' not in dict:
        return result(success=0, error_code=-1, error_msg="name is null")
    if 'code' not in dict:
        return result(success=0, error_code=-1, error_msg="code is null")
    # bool去掉
    #is_bool = 0
    #if dict['is_bool']:
        #is_bool = dict['is_bool']
    # is_expand = int(dict['is_expand'])
    if FacilityType.get_facility_type_by_name(dict["name"]):
        return result(success=0, error_code=-1, error_msg="设施类型名称已存在")
    if FacilityType.get_facility_type_by_code(dict["code"]):
        return result(success=0, error_code=-1, error_msg="设施类型编号已存在")
    #facility_type.is_bool = is_bool
    facility_type = FacilityType()
    try:
        facility_type.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-1, error_msg=str(e))
    if facility_type.save():
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route("/edit/", methods=["GET", "POST"])
def edit_facility_type(*args, **kargs):
    """编辑设施类型列表"""
    """
        {
        "id":1,
        "name":"jdd",
        "code":"21dddX",
        "description":"djhhh",
        "icon":"dddfdf",
        "dis_order":1,
        "status":0
        }
    """
    a = request.data
    try:
        dict = json.loads(a.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    # is_bool = int(dict['is_bool'])
    facility_type = FacilityType().get_entity_by_id(dict["id"])
    if not facility_type:
        result(success=0, error_code=-2, error_msg="指定设施类型异常")
    if facility_type.name != dict["name"] and FacilityType.get_facility_type_by_name(dict["name"]):
        return result(success=0, error_code=-1, error_msg="设施类型名称已存在")
    if facility_type.code!= dict["code"] and FacilityType.get_facility_type_by_code(dict["name"]):
        return result(success=0, error_code=-1, error_msg="设施类型编号已存在")
    try:
        facility_type.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))
    # facility_type.is_bool = is_bool
    # 对父id进行操作进行
    if facility_type.save():
        return result(success=1)
    else:
        return result(success=-3, error_msg="未知错误")

@mod.route("/search/",methods=["POST"])
def search_facility_type():
    """
    查询facility_type
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    receive = request.data
    try:
        data = json.loads(receive.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if 'query_word' in data:
        query_word = data['query_word']
    else:
        return result(success=0, error_code=-9, error_msg="数据格式错误")
    facility_types = FacilityType.search(query_word)
    return jsonify(facility_types)